import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import { Loading } from 'element-ui'
const baseURL = process.env.VUE_APP_BASE_API
const Qs = require('qs')

// 创建axios实例
const service = axios.create({
  // baseURL: "/api", // 跨域测试测试
  baseURL: baseURL, // 发布
  timeout: 5000 // 请求超时时间
})

const whiteApi = ['/'] // 不携带token接口
let MessageConfirmflag = true // 多个请求token失效时候 只显示一次异常
let requestData
let loadingE
// request拦截器
service.interceptors.request.use(
  request => {
    requestData = request
    if (request.isLoading) {
      loadingE = Loading.service({
        lock: true,
        text: '数据处理中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.1)'
      })
    }

    if (request.isParams) {
      request.params = request.data
    }
    if (store.getters.token) {
      request.headers['X-BUSINESS-TOKEN'] = getToken() // 请求携带自定义token
    }
    return request
  },
  error => {
    // request error
    Promise.reject(error)
  }
)
// response 拦截器
service.interceptors.response.use(
  response => {
    // code为非0是抛错
    if (requestData.isLoading) loadingE.close()// 停止页面loading
    const res = response.data
    if (res.code !== 0) {
      // 40001:非法的token; 40002:其他客户端登录了;
      if (res.code === 40001 || res.code === 40002) {
        if (MessageConfirmflag) {
          MessageConfirmflag = false
          MessageBox.confirm(
            '你已被登出，可以取消继续留在该页面，或者重新登录',
            '确定登出',
            {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            store.dispatch('FedLogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          }).catch(() => {
            MessageConfirmflag = true
          })
        }
      } else {
        Message({
          message: res.msg,
          type: 'error',
          duration: 2 * 1000
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    if (requestData.isLoading) loadingE.close()// 停止页面loading
    Message({
      message: '[NET_ERROR]' + error.msg,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default function khReqMethod({ url, data, method, isParams, isLoading }) {
  return service({
    url: url,
    method: method || 'post',
    data: data || {},
    isParams: isParams || false,
    isLoading: isLoading || false
  })
}
